package com.canvas.service.user;

import com.canvas.dto.ServiceResult;
import com.canvas.dto.UserDTO;
import com.canvas.pojo.Role;
import com.canvas.pojo.User;
import com.canvas.repository.RoleRepository;
import com.canvas.repository.UserRepository;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 宗恣
 * @Date: 2018/8/31 0031 15:23
 */
@Service
public class IUserServiceImpl implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private ModelMapper modelMapper;

    @Override
    public User findUserByName(String userName) {

        User user = userRepository.findUserByName(userName);
        if (null == user) {
            return null;
        }

        List<Role> roles = roleRepository.findRoleByUserId(user.getId());

        if (null == roles || roles.isEmpty()) {
            throw new DisabledException("权限非法");
        }

        List<GrantedAuthority> authorities = roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
//                .map(role -> new SimpleGrantedAuthority(role.getName()))
                .collect(Collectors.toList());

        user.setAuthorityList(authorities);

        return user;
    }

    @Override
    public ServiceResult<UserDTO> findById(Long adminId) {

        User user = userRepository.findById(adminId).get();
        if (null == user) {
            return ServiceResult.notFound();
        }
        UserDTO userDTO = modelMapper.map(user, UserDTO.class);

        return ServiceResult.of(userDTO);
    }
}
